<template>
  <!-- 文件导入对话框 -->
  <el-dialog
    class="dia-style"
    :title="title"
    :visible.sync="open"
    width="600px"
    :close-on-click-modal="false"
    append-to-body
    :modal-append-to-body="false"
    @close="cancel">
    <el-upload
      ref="upload"
      class="dia-up"
      :accept="accept"
      :data="upData"
      :headers="upload.headers"
      :action="url"
      :class="hiddenList ? 'no-list' : ''"
      :disabled="upload.isUploading"
      :on-change="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      :multiple="multiple"
      drag
      v-bind="$attrs">
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div v-if="accept">
        <span>支持扩展名：{{ accept }}</span>
      </div>
    </el-upload>
    <slot />
    <div slot="footer" class="dialog-footer">
      <el-button v-if="code == 201" type="text" style="color: #1c84c6" @click="importExcelErrorLog"
        >查看错误信息（下载文件）</el-button
      >
      <el-button type="primary" :icon="loading ? 'el-icon-loading' : ''" @click="submitFileForm">保 存</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken, TokenKey } from '@/utils/auth'
import { upload } from '@/utils/request'
export default {
  props: {
    url: {
      type: String,
      default: '',
    },
    accept: {
      type: String,
      default: '.xlsx',
    },
    title: {
      type: String,
      default: '上传',
    },
    successDesc: {
      type: String,
      default: '',
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    autoSubmit: {
      type: Boolean,
      default: false,
    },
    hiddenList: {
      type: Boolean,
      default: false,
    },
    otherData: {
      type: Object,
      default: () => {},
    },
    upData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      upId: null,
      loading: false,
      code: 200,
      errorUrl: '',
      fileList: [],
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: true,
        // 设置上传的请求头部
        headers: { [TokenKey]: getToken() },
      },
    }
  },
  methods: {
    show(e) {
      this.upId = e
      this.open = true
    },
    // 文件上传中处理
    handleFileUploadProgress(file, fileList) {
      this.fileList = fileList.map((item) => {
        return { file: item.raw }
      })
      this.$emit('handleFile', file)
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      )
    },

    // 提交上传文件
    submitFileForm() {
      this.loading = true
      if (this.autoSubmit) {
        this.$emit('submit')
        return
      }
      if (this.fileList.length === 0) {
        this.$message.warning('请选择文件')
        this.loading = false
        return
      }
      const form = new FormData()
      this.fileList.forEach((item, key) => {
        form.append('file', item.file)
      })
      if (this.upId) {
        form.append('taskId', this.upId)
      }
      upload(this.url, form)
        .then((res) => {
          if (!res) {
            this.$message.success('上传成功')
            this.cancel()
            this.$emit('submit')
            this.$emit('assetup', res)
            this.loading = false
            return
          }
          this.code = res.code
          // eslint-disable-next-line
          if (res.code == 201) {
            this.errorUrl = window.baseUrl.asset + res.data.fileUrl
            this.$message.warning(res.msg + '\n' + res.data.msg)
            this.$emit('submit')
            this.$emit('assetup', res)
          } else {
            this.code = 200
            this.$message.success(this.successDesc || res)
            if (res.length > 0) {
              this.$emit('submit', { fileName: res[0].name, fileUrl: res[0].url, oData: this.otherData })
              this.$emit('assetup', res)
            } else {
              this.$emit('submit')
              this.$emit('assetup', res)
            }

            this.cancel()
          }
          this.loading = false
        })
        .catch((err) => {
          console.log(err)
          this.$message.warning('文件上传失败')
          this.$refs.upload.clearFiles()
          this.code = 200
          this.loading = false
        })
    },
    //   取消
    cancel() {
      this.fileList = []
      this.code = 200
      this.$refs.upload.clearFiles()
      this.errorUrl = {}
      this.open = false
      this.$emit('handleFile', {})
      this.loading = false
    },
    importExcelErrorLog() {
      this.gDownload(this.errorUrl, {}, 'ImportExcelErrorLog.txt')
    },
  },
}
</script>

  <style lang="scss" scoped>
.dia-up {
  // text-align: center;
}
.no-list ::v-deep {
  .el-upload-list {
    display: none;
  }
}
::v-deep {
  .el-upload-dragger {
    width: 550px;
  }
  .el-dialog__body {
    display: flex;
    flex-direction: column;
    div {
      .targetTable {
        margin-top: -20px;
        margin-bottom: -20px;
      }
    }
  }
}
</style>

